<template>
    <div class="monitor-container">
        <!-- 左侧车辆列表 -->
        <div class="vehicle-list">
            <!-- 搜索框 -->
            <div class="search-box">
                <el-input v-model="searchQuery" placeholder="请输入车牌号搜索" prefix-icon="el-icon-search" clearable
                    @input="getVehicles">
                </el-input>
            </div>

            <div class="vehicle-item" v-for="item in vehicles" :key="item.id" @click="showRoute(item.id)">
                <div class="vehicle-info">
                    <span class="plate-num">運單號：{{ item.waybillId }}</span>
                    <span class="time">車牌號：{{ item.licensePlate }}</span>
                    <span class="status">司機：{{ item.driverName }}</span>
                </div>
            </div>
            <!-- 分页组件 -->
            <div class="pagination-container">
                <el-pagination small @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pageNum" :page-sizes="[10, 20, 30, 40]" :page-size="pageSize"
                    layout="total, prev, pager, next, jumper" :total="total" background>
                </el-pagination>
            </div>
        </div>

        <!-- 右侧地图区域 -->
        <div class="map-container" id="mapContainer"></div>
    </div>
</template>

<script>
import AMapLoader from '@/mapJs/index.js'
import axios from 'axios'

export default {
    name: 'Monitor',
    data() {
        return {
            map: null,
            geocoder: null,
            searchQuery: '',
            vehicles: [],
            pageNum: 1,
            pageSize: 10,
            total: 0,
            markers: [], // 存储所有标记点
            timer: null, // 用于存储定时器
            AMap: null, // 存储AMap实例
            driving: null, // 存储路径规划实例
            polyline: null // 存储路线
        }
    },
    mounted() {
        this.getVehicles();
        this.initMap();
    },
    methods: {
        async initMap() {
            // 在mounted生命周期中初始化地图
            window._AMapSecurityConfig = {
                securityJsCode: 'cc81913ee8ba0bc70077f0c2177f4e66',
            }

            try {
                // 使用AMapLoader加载地图
                this.AMap = await AMapLoader.load({
                    key: '9052ea1c024d2ef73784eb69b2557c35',
                    version: '2.0',
                    plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.Geocoder', 'AMap.Driving'] // 添加路径规划插件
                });

                // 确保地图容器有高度
                const mapContainer = document.getElementById('mapContainer');
                if (mapContainer) {
                    mapContainer.style.height = '100%';
                    mapContainer.style.width = '100%';
                }

                this.map = new this.AMap.Map('mapContainer', {
                    zoom: 11,
                    viewMode: '2D'
                });

                // 添加比例尺和工具条控件
                this.map.addControl(new this.AMap.Scale());
                this.map.addControl(new this.AMap.ToolBar());

                // 初始化地理编码插件
                this.geocoder = new this.AMap.Geocoder({
                    city: "全国" // 城市，默认："全国"
                });

                // 初始化路径规划插件
                this.driving = new this.AMap.Driving({
                    map: this.map,
                    policy: this.AMap.DrivingPolicy.LEAST_TIME // 最快路线
                });

                // 为每个车辆添加起点和终点标记
                this.vehicles.forEach(vehicle => {
                    this.addRouteMarkers(vehicle);
                });

            } catch (e) {
                console.error('地图加载失败:', e);
            }
        },
        // 添加路线标记点和路径规划
        async addRouteMarkers(vehicle) {
            if (!this.AMap || !this.map) {
                console.error('地图未初始化');
                return;
            }

            try {
                // 获取起点坐标
                const originCoords = await this.getCoordinatesByAddress(vehicle.origin);
                // 获取终点坐标
                const destCoords = await this.getCoordinatesByAddress(vehicle.destination);

                // 创建起点标记
                const originMarker = new this.AMap.Marker({
                    position: originCoords,
                    title: '起点: ' + vehicle.origin,
                    label: {
                        content: '起',
                        direction: 'top'
                    }
                });

                // 创建终点标记
                const destMarker = new this.AMap.Marker({
                    position: destCoords,
                    title: '终点: ' + vehicle.destination,
                    label: {
                        content: '终',
                        direction: 'top'
                    }
                });

                this.markers.push(originMarker, destMarker);
                this.map.add([originMarker, destMarker]);
                
                // 规划路线
                this.driving.search(
                    originCoords,
                    destCoords,
                    (status, result) => {
                        if (status === 'complete') {
                            console.log('路径规划成功');
                        } else {
                            console.error('路径规划失败:', result);
                        }
                    }
                );
                
                // 将地图中心设置为起点位置
                this.map.setCenter(originCoords);
                this.map.setFitView();

            } catch (error) {
                console.error('添加路线标记失败:', error);
            }
        },

        // 显示指定运单的路线
        async showRoute(id) {
            // 清除现有标记和定时器
            this.clearMarkers();
            if(this.timer) {
                clearInterval(this.timer);
            }
            
            // 从vehicles中获取运单详情
            const waybill = this.vehicles.find(v => v.id === id);
            if(waybill) {
                await this.addRouteMarkers(waybill);
                
                // 设置定时器，每30秒更新一次位置
                this.timer = setInterval(async () => {
                    await this.addRouteMarkers(waybill);
                }, 30000);
            }
        },

        // 清除所有标记点和路线
        clearMarkers() {
            if (this.map && this.markers.length > 0) {
                this.markers.forEach(marker => {
                    this.map.remove(marker);
                });
                this.markers = [];
            }
            if (this.driving) {
                this.driving.clear();
            }
        },

        // 根据地址获取坐标的方法
        getCoordinatesByAddress(address) {
            return new Promise((resolve, reject) => {
                if (!this.geocoder) {
                    reject('地理编码插件未初始化');
                    return;
                }

                this.geocoder.getLocation(address, (status, result) => {
                    if (status === 'complete' && result.geocodes.length) {
                        const lnglat = result.geocodes[0].location;
                        resolve([lnglat.lng, lnglat.lat]);
                    } else {
                        reject('地理编码失败');
                    }
                });
            });
        },
        getVehicles() {
            const params = {
                waybillId: this.searchQuery,
            }
            axios.post('/api/om/waybill/getAll?pageNum=' + this.pageNum + '&pageSize=' + this.pageSize, params).then(res => {
                this.vehicles = res.data.records;
                this.total = res.data.total;
                // 清除现有标记并添加新的标记
                this.clearMarkers();
                this.vehicles.forEach(vehicle => {
                    this.addRouteMarkers(vehicle);
                });
            })
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getVehicles();
        },
        handleCurrentChange(val) {
            this.pageNum = val;
            this.getVehicles();
        },
    },
    beforeDestroy() {
        // 组件销毁前清除定时器
        if(this.timer) {
            clearInterval(this.timer);
        }
        if (this.map) {
            this.map.destroy();
            this.map = null;
        }
    }
}
</script>

<style scoped>
.monitor-container {
    display: flex;
    height: 100vh;
    /* 使用视口高度确保容器有高度 */
    width: 100%;
    position: relative;
}

.vehicle-list {
    width: 300px;
    background: #fff;
    border-right: 1px solid #e8e8e8;
    overflow-y: auto;
    display: flex;
    flex-direction: column;
}

.search-box {
    padding: 15px;
    border-bottom: 1px solid #e8e8e8;
}

.vehicle-item {
    padding: 15px;
    border-bottom: 1px solid #f0f0f0;
    cursor: pointer;
}

.vehicle-item:hover {
    background: #f5f5f5;
}

.vehicle-info {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.plate-num {
    font-size: 16px;
    font-weight: bold;
}

.time,
.status {
    font-size: 12px;
    color: #999;
}

.pagination-container {
    padding: 10px;
    background: #fff;
    border-top: 1px solid #e8e8e8;
    margin-top: auto;
}

.map-container {
    flex: 1;
    height: 100%;
    min-height: 500px;
    /* 设置最小高度 */
    position: relative;
}
</style>
